﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections.Concurrent;

namespace MegauploadForum
{
    public class LinkParserManager : IDisposable
    {

        #region Members

        private IList<LinksParserWorker> m_workers;
        private BlockingCollection<ParsingRequest> m_requestQueue;


        #endregion

        #region Properties

        public TimeSpan WaitBetweenTwoLinks { get; set; }

        #endregion

        #region Events

        public event EventHandler<ParsingResultEventArgs> OnParsed;

        #endregion

        #region Public Methods

        public void Init(IEnumerable<WebBrowser> webBrowsers)
        {
            m_workers = new List<LinksParserWorker>();
            m_requestQueue = new BlockingCollection<ParsingRequest>();
            foreach (WebBrowser wb in webBrowsers)
            {
                LinksParserWorker worker = new LinksParserWorker();
                worker.WaitBetweenTwoLinks = WaitBetweenTwoLinks;
                worker.OnParsed += worker_OnParsed;
                worker.WebBrowser = wb;
                worker.Queue = m_requestQueue;
                worker.Init();
                m_workers.Add(worker);
                worker.Start();
            }
        }

        
        public void ParseRequest(ParsingRequest request)
        {
            Console.WriteLine("LinkParserManager new Request");
            m_requestQueue.Add(request);
        }

        public void Dispose()
        {
            foreach (LinksParserWorker worker in m_workers)
            {
                worker.Dispose();
            }
        }

        #endregion

        #region Private Methods

        private void worker_OnParsed(object sender, ParsingResultEventArgs e)
        {
            Console.WriteLine("LinkParserManager new Result");
            if (OnParsed != null)
            {
                OnParsed(this, e);
            }
        }

        #endregion

    }

    #region Types

    public class ParsingResultEventArgs : EventArgs 
    {
        public ParsingResult Result { get; set; }
    }

	#endregion
}
